package com.haople.sso.jdbc.authentication.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.haople.sso.core.authentication.TicketAuthorization;
import com.haople.sso.core.vo.Ticket;
import com.haople.sso.core.vo.User;
import com.haople.sso.jdbc.dao.TicketDao;
import com.haople.sso.jdbc.dao.UserDao;

/**
 * 根据数据库验证票据授权情况
 * @author Administrator
 *
 */

public class DBTicketAuthorizationImpl implements TicketAuthorization {
    private static final Logger logger=Logger.getLogger(DBTicketAuthorizationImpl.class);
    
	@Autowired
	private TicketDao ticketDao;
	@Autowired
	private UserDao userDao;
	
	/**
	 * 根据传递过来的票据
	 */
	public boolean authorization(Ticket ticket) throws Exception {
		boolean flag=false;
		try {
			if(ticket==null || StringUtils.isEmpty(ticket.getTicket())){
				logger.info("---- 根据票据授权时 ---票据ticket is null ");
				return  flag;
			}
			if(StringUtils.isEmpty(ticket.getUserId())){
				logger.info("---- 根据票据授权时 ---票据ticket中的 --userId is null ");
				return  flag;
			}
			if(ticketDao.find(ticket.getTicket(), ticket.getUserId())!=null){
				flag=true;
			}
		} catch (Exception e) {
			logger.error("--根据票据授权异常---"+ticket+"---", e);
			throw e;
		}
		return flag;
	}

	
	/**
	 * 登录成功后保存票据
	 */
	public boolean save(Ticket ticket) throws Exception {
		boolean flag=false;
		try {
			if(ticket==null || StringUtils.isEmpty(ticket.getTicket())){
				logger.info("---- 保存票据时 ---票据ticket is null ");
				return  flag;
			}
			if(StringUtils.isEmpty(ticket.getUserId())){
				logger.info("----保存票据时 ---票据ticket中的 --userId is null ");
				return  flag;
			}
			User user=userDao.find(ticket.getUserId());
			if(user==null){
				logger.info("----保存票据时 ---没有此用户  --[ userId:"+ticket.getUserId()+" ]--");
				return  flag;
			}
			Integer rowNum=ticketDao.save(ticket.getTicket(), user.getUserId(),user.getUserName());
			if(rowNum>0){
				flag=true;
			}
		} catch (Exception e) {
			logger.error("--保存票据---"+ticket+"---", e);
			throw e;
		}
		return flag;
	}

	/**
	 * 获取票据
	 */
	public Ticket get(String userId) throws Exception {
		return ticketDao.find(userId);
	}

}
